<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Leaflet debug page - Detached DOM Memory Leak</title>
		<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0" />
		<link rel="stylesheet" href="../../dist/leaflet.css" />
		<link rel="stylesheet" href="../css/screen.css" />
		<script type="importmap">
			{
				"imports": {
					"leaflet": "../../dist/leaflet-src.esm.js"
				}
			}
		</script>
	</head>
	<body>
		<button id="once">Once</button>
		<button id="start">Start</button>
		<button id="stop">Stop</button>
		<script type="module">
			import {TileLayer, Map} from 'leaflet';

			let map;
			let mapDiv;
			const osm = new TileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png');

			function recreateMap() {
				// destroy previous map and div

				if (map) {
					map.remove();	// This will destroy all DOM childs from layers and controls
				}

				if (mapDiv) {
					mapDiv.parentNode.removeChild(mapDiv); // This will destroy the map div
				}

				// create new map div
				const randomDivId = `map-${new Date().getTime()}`;
				mapDiv = document.createElement('div');
				mapDiv.id = randomDivId;
				mapDiv.style.height = '200px';
				mapDiv.style.width = '200px';
				document.getElementsByTagName('body')[0].appendChild(mapDiv);
				// attach map to div
				map = new Map(randomDivId).setView([51.505, -0.09], 13);
				map.addLayer(osm);
			}

			let interval = null;

			function start() {
				interval = setInterval(recreateMap, 200);
			}

			function stop() {
				clearInterval(interval);
			}

			document.getElementById('once').addEventListener('click', recreateMap);
			document.getElementById('start').addEventListener('click', start);
			document.getElementById('stop').addEventListener('click', stop);
		</script>
	</body>
</html>
